package cool.xiaokang.familyaccount.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@Controller
@Scope("prototype")
public class LogAction extends ActionSupport {
	private static final long serialVersionUID = 2877065670381735430L;
	private static Logger LOGGER = Logger.getLogger(LogAction.class);

	public void collect() {
		HttpServletRequest request = ServletActionContext.getRequest();
		// 对get请求串解码，防止中文乱码
		String perLogInfo = null;
		try {
			perLogInfo = URLDecoder.decode(request.getQueryString(), "utf-8");
			// 请求串中各指标以&符号分割
			String[] fluxs = perLogInfo.split("\\&");
			StringBuffer buf = new StringBuffer();
			for (String flux : fluxs) {
				// 每个指标以kv形式存在，中间用=分割
				String[] kv = flux.split("=");
				String key = kv[0]; // 指标名称
				String val = kv.length == 2 ? kv[1] : ""; // 指标值
				buf.append(val + "|"); // 指标以|分割
			}
			buf.append(request.getRemoteAddr()); // 增加服务器端IP地址指标
			String loginfo = buf.toString();
			LOGGER.info(loginfo);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

}
